package com.btex.app.pager;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.btex.app.Config;
import com.btex.app.MyApplication;
import com.btex.app.R;
import com.btex.app.TradeActivity;
import com.btex.app.adapter.FirstFragmentAdapter;
import com.btex.app.entity.MyMarketInfo;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Util;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/5/18
 * @time 下午12:32
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */

public class FirstFragment extends Fragment implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    @BindView(R.id.fragmnet_first)
    RecyclerView mFragmnetFirst;
    Unbinder unbinder;

    boolean isShow = false;
    @BindView(R.id.fragment_tv_type)
    TextView mFragmentTvType;
    @BindView(R.id.fragment_imag_type_first)
    ImageView mFragmentImagTypeFirst;
    @BindView(R.id.fragment_lin_type_first)
    LinearLayout mFragmentLinTypeFirst;
    @BindView(R.id.fragment_imag_zuixin_first)
    ImageView mFragmentImagZuixinFirst;
    @BindView(R.id.fragment_lin_zuixin_first)
    LinearLayout mFragmentLinZuixinFirst;
    @BindView(R.id.fragment_imag_zhangdie_first)
    ImageView mFragmentImagZhangdieFirst;
    @BindView(R.id.fragment_lin_zhangdie_first)
    LinearLayout mFragmentLinZhangdieFirst;
    private SharedPreferencesUtil sp;

    private PreferencesCookieStore cookieStore;

    private FirstFragmentAdapter mFirstFragmentAdapter;
    private boolean mIsVisibleToUser;
    private MicroAVLIDialog mMicroAVLIDialog;
    private List<MyMarketInfo.DataBean> mData;
    public boolean isChengjiao = false;
    public boolean isNew = false;

    public static Fragment newInstance() {
        FirstFragment fragment = new FirstFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.first_fragment_layout, null);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        sp = SharedPreferencesUtil.getSharedPreferences(getActivity());
        isShow = true;
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initRecy();
//        getInfo();


    }

    private void initRecy() {
        mFirstFragmentAdapter = new FirstFragmentAdapter(null);
        mFragmnetFirst.setLayoutManager(new LinearLayoutManager(getActivity()));
        mFragmnetFirst.setAdapter(mFirstFragmentAdapter);
        mFirstFragmentAdapter.setOnItemClickListener(this);
        mFirstFragmentAdapter.setOnItemChildClickListener(this);
    }


    @Override
    public void onResume() {
        super.onResume();

        getInfo();
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, 0);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);

    }

    public void getInfo() {


        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(MyApplication.getContextObject(), sp);

        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.GET_COLLECT_MARKET + "?rnd=" + String.valueOf(num)).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body();
//                Log.i("wegfuwefhuiwle===FIRST", result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
                        Gson gson = new Gson();
                        MyMarketInfo myMarketInfo = gson.fromJson(result, MyMarketInfo.class);
                        if (myMarketInfo.getData().size() == 0) {

                            mFirstFragmentAdapter = new FirstFragmentAdapter(null);
                            if (mFragmnetFirst != null) {
                                mFragmnetFirst.setLayoutManager(new LinearLayoutManager(getActivity()));
                                mFirstFragmentAdapter.setEmptyView(R.layout.item_empty, mFragmnetFirst);
                                mFirstFragmentAdapter.setOnItemClickListener(FirstFragment.this);
                                mFirstFragmentAdapter.setOnItemChildClickListener(FirstFragment.this);
                                mFragmnetFirst.setAdapter(mFirstFragmentAdapter);
                            }

                        } else {

                            mData = myMarketInfo.getData();
                            mFirstFragmentAdapter.replaceData(mData);
                        }

                    } else {
                        if (mFirstFragmentAdapter != null) {
                            if (mFragmnetFirst != null) {
                                mFirstFragmentAdapter.setEmptyView(R.layout.item_empty, mFragmnetFirst);
                            }

                        }

                    }
                } catch (JSONException e) {


                }
            }
        });

//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_COLLECT_MARKET + "?rnd=" + String.valueOf(num), new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//                String result = responseInfo.result;
////                Log.i("wegfuwefhuiwle===FIRST", result);
//
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
//                        Gson gson = new Gson();
//                        MyMarketInfo myMarketInfo = gson.fromJson(result, MyMarketInfo.class);
//                        if (myMarketInfo.getData().size() == 0) {
//
//                            mFirstFragmentAdapter = new FirstFragmentAdapter(null);
//                            if (mFragmnetFirst != null) {
//                                mFragmnetFirst.setLayoutManager(new LinearLayoutManager(getActivity()));
//                                mFirstFragmentAdapter.setEmptyView(R.layout.item_empty, mFragmnetFirst);
//                                mFirstFragmentAdapter.setOnItemClickListener(FirstFragment.this);
//                                mFirstFragmentAdapter.setOnItemChildClickListener(FirstFragment.this);
//                                mFragmnetFirst.setAdapter(mFirstFragmentAdapter);
//                            }
//
//                        } else {
//
//                            mData = myMarketInfo.getData();
//                            mFirstFragmentAdapter.replaceData(mData);
//                        }
//
//                    } else {
//                        if (mFirstFragmentAdapter != null) {
//                            if (mFragmnetFirst != null) {
//                                mFirstFragmentAdapter.setEmptyView(R.layout.item_empty, mFragmnetFirst);
//                            }
//
//                        }
//
//                    }
//                } catch (JSONException e) {
//
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {

        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            mIsVisibleToUser = true;
        } else {
            mIsVisibleToUser = false;
        }
//        if (isVisibleToUser) {
//            Log.i("lkwejfwie", "uewhfw");
//            if (isShow) {
//                getInfo();
//            }
//
//        } else {
//            //相当于Fragment的onPause
//        }
    }

    @Subscribe
    public void onEvent(String event) {

        if (event.equals("chengjiao")) {

            mFragmentTvType.setText("成交量");
            if (mFirstFragmentAdapter != null) {
                mFirstFragmentAdapter.notifyDataSetChanged();
            }


        } else if (event.equals("zhangdie")) {

            mFragmentTvType.setText("涨跌幅");
            if (mFirstFragmentAdapter != null) {
                mFirstFragmentAdapter.notifyDataSetChanged();
            }
        }

        if (event.equals("shoucang")) {
            getInfo();

        }


    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

        MyMarketInfo.DataBean dataBean = (MyMarketInfo.DataBean) adapter.getData().get(position);
        String type = dataBean.getType();
        String danwei = dataBean.getDanwei();
        Intent intent = new Intent(getActivity(), TradeActivity.class);
        intent.putExtra("pair", type + "_" + danwei);
        startActivity(intent);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {


        mMicroAVLIDialog = new MicroAVLIDialog(getActivity());
        mMicroAVLIDialog.show();

        MyMarketInfo.DataBean bean = (MyMarketInfo.DataBean) adapter.getData().get(position);
        String collect_id = bean.getCollect_id();
        cookieStore = CookieTool.getCookieStore(getActivity(), sp);
        RequestParams params = new RequestParams();
        params.addBodyParameter("collect_id", collect_id);


        OkGo.<String>post(Config.DEl_COLLECT).params("collect_id", collect_id).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {

                if (mMicroAVLIDialog != null) {
                    mMicroAVLIDialog.dismiss();
                }

                String result = response.body();

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
                        mMicroAVLIDialog.dismiss();
//                        Toast.makeText(getActivity(), R.string.del_info, Toast.LENGTH_SHORT).show();
//                        Snackbar snackbar = Util.ShortSnackbar(mFragmentImagTypeFirst, getString(R.string.del_info), Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//                        snackbar.show();
                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.bg_green), getString(R.string.del_info));
                        getInfo();

                    } else {
                        if (mMicroAVLIDialog != null) {
                            mMicroAVLIDialog.dismiss();
                        }

//                        Toast.makeText(getActivity(), jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });



//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.DEl_COLLECT, params, new RequestCallBack<String>() {
//
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                if (mMicroAVLIDialog != null) {
//                    mMicroAVLIDialog.dismiss();
//                }
//
//                String result = responseInfo.result;
//
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
//                        mMicroAVLIDialog.dismiss();
////                        Toast.makeText(getActivity(), R.string.del_info, Toast.LENGTH_SHORT).show();
////                        Snackbar snackbar = Util.ShortSnackbar(mFragmentImagTypeFirst, getString(R.string.del_info), Color.parseColor("#ffffff"), Color.parseColor("#272736"));
////                        snackbar.show();
//                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.bg_green), getString(R.string.del_info));
//                        getInfo();
//
//                    } else {
//                        if (mMicroAVLIDialog != null) {
//                            mMicroAVLIDialog.dismiss();
//                        }
//
////                        Toast.makeText(getActivity(), jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
//                    }
//
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//
//            }
//
//            @Override
//            public void onLoading(long total, long current, boolean isUploading) {
//                super.onLoading(total, current, isUploading);
//
//            }
//        });

    }

    private Handler handler = new Handler() {

    };
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {


            if (mIsVisibleToUser) {

                getInfo();
            }

            handler.postDelayed(this, 5000);
        }
    };

    @OnClick({R.id.fragment_lin_type_first, R.id.fragment_lin_zuixin_first, R.id.fragment_lin_zhangdie_first})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fragment_lin_type_first:
                break;
            case R.id.fragment_lin_zuixin_first:


                if (mData == null) {
                    return;
                }

                if (isNew) {
                    mFragmentImagZuixinFirst.setBackground(getResources().getDrawable(R.mipmap.jian_xia));

                    Collections.sort(mData, new Comparator<MyMarketInfo.DataBean>() {
                        @Override
                        public int compare(MyMarketInfo.DataBean ethBean, MyMarketInfo.DataBean t1) {

                            String zhangdie = ethBean.getTicker().getTrade_price();
                            String zhangdie1 = t1.getTicker().getTrade_price();
                            Double v = Double.valueOf(zhangdie);
                            Double v1 = Double.valueOf(zhangdie1);
                            if (v > v1) {
                                return 1;
                            } else if (v < v1) {
                                return -1;
                            } else {
                                return 0;
                            }

                        }
                    });

                    mFirstFragmentAdapter = new FirstFragmentAdapter(null);
                    mFirstFragmentAdapter.setOnItemChildClickListener(this);
                    mFirstFragmentAdapter.setOnItemClickListener(this);
                    mFragmnetFirst.setAdapter(mFirstFragmentAdapter);
                    mFirstFragmentAdapter.replaceData(mData);
                    isNew = !isNew;

                } else {
                    mFragmentImagZuixinFirst.setBackground(getResources().getDrawable(R.mipmap.jian_shang));
                    Collections.sort(mData, new Comparator<MyMarketInfo.DataBean>() {
                        @Override
                        public int compare(MyMarketInfo.DataBean ethBean, MyMarketInfo.DataBean t1) {

                            String zhangdie = ethBean.getTicker().getTrade_price();
                            String zhangdie1 = t1.getTicker().getTrade_price();

                            Double v = Double.valueOf(zhangdie);
                            Double v1 = Double.valueOf(zhangdie1);


                            if (v > v1) {
                                return -1;
                            } else if (v < v1) {
                                return 1;
                            } else {
                                return 0;
                            }

                        }
                    });

                    mFirstFragmentAdapter = new FirstFragmentAdapter(null);
                    mFirstFragmentAdapter.setOnItemChildClickListener(this);
                    mFirstFragmentAdapter.setOnItemClickListener(this);
                    mFragmnetFirst.setAdapter(mFirstFragmentAdapter);
                    mFirstFragmentAdapter.replaceData(mData);
                    isNew = !isNew;
                }


                break;
            case R.id.fragment_lin_zhangdie_first:


                if (mData == null) {
                    return;
                }

                if (isNew) {
                    mFragmentImagZhangdieFirst.setBackground(getResources().getDrawable(R.mipmap.jian_xia));

                    Collections.sort(mData, new Comparator<MyMarketInfo.DataBean>() {
                        @Override
                        public int compare(MyMarketInfo.DataBean ethBean, MyMarketInfo.DataBean t1) {

                            String zhangdie = ethBean.getTicker().getTrade_price();
                            String zhangdie1 = t1.getTicker().getTrade_price();
                            Double v = Double.valueOf(zhangdie);
                            Double v1 = Double.valueOf(zhangdie1);
                            if (v > v1) {
                                return 1;
                            } else if (v < v1) {
                                return -1;
                            } else {
                                return 0;
                            }

                        }
                    });

                    mFirstFragmentAdapter = new FirstFragmentAdapter(null);
                    mFirstFragmentAdapter.setOnItemChildClickListener(this);
                    mFirstFragmentAdapter.setOnItemClickListener(this);
                    mFragmnetFirst.setAdapter(mFirstFragmentAdapter);
                    mFirstFragmentAdapter.replaceData(mData);
                    isNew = !isNew;

                } else {
                    mFragmentImagZhangdieFirst.setBackground(getResources().getDrawable(R.mipmap.jian_shang));
                    Collections.sort(mData, new Comparator<MyMarketInfo.DataBean>() {
                        @Override
                        public int compare(MyMarketInfo.DataBean ethBean, MyMarketInfo.DataBean t1) {

                            String zhangdie = ethBean.getTicker().getTrade_price();
                            String zhangdie1 = t1.getTicker().getTrade_price();

                            Double v = Double.valueOf(zhangdie);
                            Double v1 = Double.valueOf(zhangdie1);


                            if (v > v1) {
                                return -1;
                            } else if (v < v1) {
                                return 1;
                            } else {
                                return 0;
                            }

                        }
                    });

                    mFirstFragmentAdapter = new FirstFragmentAdapter(null);
                    mFirstFragmentAdapter.setOnItemChildClickListener(this);
                    mFirstFragmentAdapter.setOnItemClickListener(this);
                    mFragmnetFirst.setAdapter(mFirstFragmentAdapter);
                    mFirstFragmentAdapter.replaceData(mData);
                    isNew = !isNew;
                }

                break;
        }
    }
}
